<template>
  <div class="rate-form">
    <!-- 评分标题 -->
    <div class="rate-header">
      <h3 class="rate-title">{{ title }}</h3>
      <p v-if="description" class="rate-description">
        {{ description }}
      </p>
    </div>

    <!-- 评分项目 -->
    <div class="rate-items">
      <!-- 总体评分 -->
      <div class="rate-item">
        <div class="item-label">总体评分</div>
        <div class="item-content">
          <el-rate
            v-model="form.overall"
            :max="5"
            :colors="rateColors"
            :texts="rateTexts"
            show-text
            show-score
          />
        </div>
      </div>

      <!-- 多维度评分 -->
      <template v-if="dimensions?.length">
        <div
          v-for="dimension in dimensions"
          :key="dimension.key"
          class="rate-item"
        >
          <div class="item-label">{{ dimension.label }}</div>
          <div class="item-content">
            <el-rate
              v-model="form.dimensions[dimension.key]"
              :max="5"
              :colors="rateColors"
              :texts="rateTexts"
              show-text
              show-score
            />
          </div>
        </div>
      </template>
    </div>

    <!-- 评价内容 -->
    <div class="rate-content">
      <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
        <!-- 评价标签 -->
        <el-form-item v-if="tags?.length" label="评价标签（可多选）">
          <div class="tags-wrapper">
            <el-check-tag
              v-for="tag in tags"
              :key="tag"
              :checked="form.tags.includes(tag)"
              class="tag-item"
              @change="(checked) => handleTagChange(tag, checked)"
            >
              {{ tag }}
            </el-check-tag>
          </div>
        </el-form-item>

        <!-- 评价内容 -->
        <el-form-item label="评价内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            :maxlength="maxLength"
            :placeholder="placeholder"
            show-word-limit
          />
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item label="上传图片">
          <el-upload
            action="/api/upload/image"
            list-type="picture-card"
            :limit="maxImages"
            :file-list="form.images"
            :before-upload="beforeImageUpload"
            :on-success="handleImageSuccess"
            :on-remove="handleImageRemove"
            :on-error="handleImageError"
          >
            <template #default>
              <el-icon><Plus /></el-icon>
              <div class="upload-text">点击上传</div>
            </template>
            <template #file="{ file }">
              <img :src="file.url" class="upload-image" />
            </template>
          </el-upload>
          <div class="upload-tip">
            最多上传 {{ maxImages }} 张图片，每张图片不超过 2MB
          </div>
        </el-form-item>

        <!-- 匿名选项 -->
        <el-form-item>
          <el-checkbox v-model="form.isAnonymous"> 匿名发布 </el-checkbox>
          <el-tooltip
            content="开启后，您的评价将以匿名形式展示"
            placement="right"
          >
            <el-icon class="info-icon"><InfoFilled /></el-icon>
          </el-tooltip>
        </el-form-item>
      </el-form>
    </div>

    <!-- 提交按钮 -->
    <div class="form-actions">
      <el-button
        type="primary"
        :loading="submitting"
        :disabled="!isValid"
        @click="handleSubmit"
      >
        提交评价
      </el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Plus, InfoFilled } from "@element-plus/icons-vue";

const props = defineProps({
  title: {
    type: String,
    default: "发表评价",
  },
  description: {
    type: String,
    default: "",
  },
  dimensions: {
    type: Array,
    default: () => [],
  },
  tags: {
    type: Array,
    default: () => [],
  },
  placeholder: {
    type: String,
    default: "请分享您的使用体验和建议...",
  },
  maxLength: {
    type: Number,
    default: 500,
  },
  maxImages: {
    type: Number,
    default: 9,
  },
  initialValue: {
    type: Object,
    default: null,
  },
});

const emit = defineEmits(["submit", "cancel"]);

const formRef = ref(null);
const submitting = ref(false);

// 评分颜色
const rateColors = ["#ff4d4f", "#faad14", "#52c41a"];

// 评分文案
const rateTexts = ["差", "一般", "好", "很好", "非常好"];

// 表单数据
const form = ref({
  overall: 0,
  dimensions: {},
  tags: [],
  content: "",
  images: [],
  isAnonymous: false,
});

// 表单校验规则
const rules = {
  content: [
    { required: true, message: "请填写评价内容", trigger: "blur" },
    { min: 10, message: "评价内容不能少于10个字符", trigger: "blur" },
  ],
};

// 表单是否有效
const isValid = computed(() => {
  return form.value.overall > 0 && form.value.content.length >= 10;
});

// 初始化维度评分
onMounted(() => {
  if (props.dimensions?.length) {
    props.dimensions.forEach((dimension) => {
      form.value.dimensions[dimension.key] = 0;
    });
  }

  // 如果有初始值，填充表单
  if (props.initialValue) {
    form.value = {
      ...form.value,
      ...props.initialValue,
    };
  }
});

// 处理标签变化
const handleTagChange = (tag, checked) => {
  const tags = form.value.tags;
  const index = tags.indexOf(tag);

  if (checked && index === -1) {
    tags.push(tag);
  } else if (!checked && index > -1) {
    tags.splice(index, 1);
  }
};

// 图片上传前检查
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 图片上传成功
const handleImageSuccess = (response, uploadFile) => {
  form.value.images.push({
    name: uploadFile.name,
    url: response.url,
  });
  ElMessage.success("图片上传成功");
};

// 图片上传失败
const handleImageError = () => {
  ElMessage.error("图片上传失败");
};

// 移除图片
const handleImageRemove = (uploadFile) => {
  const index = form.value.images.findIndex(
    (image) => image.url === uploadFile.url,
  );
  if (index > -1) {
    form.value.images.splice(index, 1);
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    if (form.value.overall === 0) {
      ElMessage.warning("请选择总体评分");
      return;
    }

    submitting.value = true;
    await emit("submit", form.value);
    ElMessage.success("评价提交成功");
  } catch (error) {
    console.error("表单验证失败:", error);
    ElMessage.error("表单验证失败");
  } finally {
    submitting.value = false;
  }
};

// 取消
const handleCancel = () => {
  emit("cancel");
};
</script>

<style lang="scss" scoped>
.rate-form {
  @apply space-y-6;

  .rate-header {
    .rate-title {
      @apply text-lg font-medium text-gray-900 mb-1;
    }

    .rate-description {
      @apply text-sm text-gray-500;
    }
  }

  .rate-items {
    @apply space-y-4;

    .rate-item {
      @apply flex items-center;

      .item-label {
        @apply w-24 text-gray-600;
      }

      .item-content {
        @apply flex-1;
      }
    }
  }

  .rate-content {
    @apply bg-white rounded-lg p-6;

    .tags-wrapper {
      @apply flex flex-wrap gap-2;

      .tag-item {
        @apply cursor-pointer;

        &.is-checked {
          @apply bg-primary-50 text-primary-600 border-primary-600;
        }
      }
    }

    .upload-image {
      @apply w-full h-full object-cover;
    }

    .upload-tip {
      @apply mt-2 text-sm text-gray-500;
    }

    .info-icon {
      @apply ml-1 text-gray-400 cursor-help;
    }
  }

  .form-actions {
    @apply flex justify-end space-x-2;
  }
}
</style>
